import utils from "./utils.js"
import Dep from './dep.js'

function Watcher(key, vm, cb) {
  this.key = key
  this.vm = vm
  this.cb = cb
  this.oldValue = this.getOldValue()
}

Watcher.prototype.getOldValue = function () {
  Dep.target = this
  const oldVal = utils.getValue(this.key, this.vm)
  Dep.target = null
  return oldVal
}

Watcher.prototype.update = function () {
  const newVal = utils.getValue(this.key, this.vm)
  if (newVal !== this.oldValue) {
    this.cb(newVal)
  }
}

export default Watcher